package org.pms.demo.webservice.exception;

import org.apache.log4j.Logger;
import org.apache.shiro.ShiroException;
import org.pms.demo.webservice.base.ExceptionCode;
import org.pms.demo.webservice.utils.ExceptionUtil;
import org.pms.demo.webservice.utils.ProjectUtils;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

/**
 * Created by laijianpeng on 17/10/20.
 */
@Provider
public class ExceptionMapperSupport implements ExceptionMapper<Exception> {
    private static final Logger LOGGER = Logger
            .getLogger(ExceptionMapperSupport.class);

    private static final String CONTEXT_ATTRIBUTE = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;

    @Context
    private HttpServletRequest request;

    @Context
    private ServletContext servletContext;

    /**
     * 异常处理
     *
     * @param exception
     * @return 异常处理后的Response对象
     */
    @Override
    public Response toResponse(Exception exception) {
        // 处理unchecked exception
        String msg = String.valueOf(exception.getMessage());
        if (exception instanceof ShiroException) {
            ShiroException exp = (ShiroException) exception;
            msg = ExceptionUtil.getExceptionCode(exp.toString());
        }

        return Response.ok(ProjectUtils.getErrorMsg(msg), MediaType.TEXT_PLAIN).status(200)
                .build();
    }
}
